<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-left">
        <h1>老薛个人SSH网页工具</h1>
      </div>
      <div class="header-right">
        <span class="username">{{ authStore.username }}</span>
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </div>
    </div>

    <div class="main-content">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h2>服务器列表</h2>
          <el-button type="primary" size="small" :icon="Plus" @click="showAddDialog = true">
            添加
          </el-button>
        </div>

        <div class="server-list">
          <div v-if="serversStore.loading" class="loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <div v-else-if="serversStore.servers.length === 0" class="empty">
            <el-empty description="暂无服务器" />
          </div>

          <div v-else>
            <div
              v-for="server in serversStore.servers"
              :key="server.id"
              class="server-card"
              :class="{ active: activeTerminals.some(t => t.serverId === server.id) }"
              @click="openTerminal(server)"
            >
              <div class="server-info">
                <div class="server-name">
                  {{ server.name }}
                  <el-tag v-if="activeTerminals.some(t => t.serverId === server.id)" type="success" size="small">
                    已连接
                  </el-tag>
                </div>
                <div class="server-host">{{ server.host}}:{{ server.port }}</div>
                <div v-if="server.expire_date" class="server-expire" :class="getExpireClass(server.expire_date)">
                  {{ formatExpireDate(server.expire_date) }}
                </div>
              </div>
              <div class="server-actions" @click.stop>
                <el-button
                  size="small"
                  :icon="Edit"
                  circle
                  @click="editServer(server)"
                />
                <el-button
                  size="small"
                  type="danger"
                  :icon="Delete"
                  circle
                  @click="deleteServerConfirm(server)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主内容区 - 终端标签页 -->
      <div class="content">
        <div v-if="activeTerminals.length === 0" class="welcome">
          <div class="welcome-icon">
            <el-icon :size="80"><Monitor /></el-icon>
          </div>
          
          <h2 class="welcome-title">欢迎使用 SSH 网页工具</h2>
          <p class="welcome-subtitle">安全、便捷的远程服务器管理平台</p>
          
          <div class="feature-cards">
            <div class="feature-card">
              <el-icon :size="32" color="#409eff"><Connection /></el-icon>
              <h3>快速连接</h3>
              <p>点击左侧服务器即可自动连接</p>
            </div>
            
            <div class="feature-card">
              <el-icon :size="32" color="#67c23a"><Monitor /></el-icon>
              <h3>实时监控</h3>
              <p>CPU、内存、硬盘状态一目了然</p>
            </div>
            
            <div class="feature-card">
              <el-icon :size="32" color="#e6a23c"><Management /></el-icon>
              <h3>多服务器</h3>
              <p>支持同时管理多个服务器连接</p>
            </div>
          </div>
          
          <div class="stats-section">
            <div class="stat-item">
              <div class="stat-value">{{ serversStore.serverCount }}</div>
              <div class="stat-label">服务器总数</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-value">{{ activeTerminals.length }}</div>
              <div class="stat-label">活跃连接</div>
            </div>
          </div>
          
          <div class="quick-start">
            <el-button type="primary" size="large" :icon="Plus" @click="showAddDialog = true">
              添加服务器
            </el-button>
          </div>
        </div>

        <div v-else class="terminal-tabs">
          <el-tabs
            v-model="activeTabName"
            type="card"
            closable
            @tab-remove="closeTerminal"
          >
            <el-tab-pane
              v-for="terminal in activeTerminals"
              :key="terminal.id"
              :label="terminal.serverName"
              :name="terminal.id"
            >
              <TerminalPanel
                :server-id="terminal.serverId"
                :server-name="terminal.serverName"
                :is-active="activeTabName === terminal.id"
                @close="closeTerminal(terminal.id)"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 添加/编辑服务器对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingServer ? '编辑服务器' : '添加服务器'"
      width="500px"
    >
      <el-form
        ref="serverFormRef"
        :model="serverForm"
        :rules="serverRules"
        label-width="100px"
      >
        <el-form-item label="服务器名称" prop="name">
          <el-input v-model="serverForm.name" placeholder="例如：生产服务器" />
        </el-form-item>

        <el-form-item label="主机地址" prop="host">
          <el-input v-model="serverForm.host" placeholder="例如：192.168.1.100" />
        </el-form-item>

        <el-form-item label="端口" prop="port">
          <el-input-number v-model="serverForm.port" :min="1" :max="65535" />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="serverForm.username" placeholder="例如：root" />
        </el-form-item>

        <el-form-item label="认证方式" prop="authType">
          <el-radio-group v-model="serverForm.authType">
            <el-radio label="password">密码</el-radio>
            <el-radio label="key">密钥</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="serverForm.authType === 'password'" label="密码" prop="password">
          <el-input
            v-model="serverForm.password"
            type="password"
            show-password
            placeholder="SSH登录密码"
          />
        </el-form-item>

        <el-form-item v-if="serverForm.authType === 'key'" label="私钥" prop="privateKey">
          <el-input
            v-model="serverForm.privateKey"
            type="textarea"
            :rows="6"
            placeholder="粘贴SSH私钥内容"
          />
        </el-form-item>

        <el-form-item label="分组" prop="groupName">
          <el-input v-model="serverForm.groupName" placeholder="例如：生产环境" />
        </el-form-item>

        <el-form-item label="到期时间" prop="expireDate">
          <el-date-picker
            v-model="serverForm.expireDate"
            type="date"
            placeholder="选择到期日期（可选）"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            :clearable="true"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ editingServer ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useServersStore } from '@/stores/servers'
import { ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Loading, Monitor, Connection, Management } from '@element-plus/icons-vue'
import TerminalPanel from '@/components/TerminalPanel.vue'

const router = useRouter()
const authStore = useAuthStore()
const serversStore = useServersStore()

const showAddDialog = ref(false)
const editingServer = ref(null)
const submitting = ref(false)
const serverFormRef = ref(null)

// 终端管理
const activeTerminals = ref([])
const activeTabName = ref('')

// 服务器表单
const serverForm = ref({
  name: '',
  host: '',
  port: 22,
  username: 'root',
  authType: 'password',
  password: '',
  privateKey: '',
  groupName: 'default',
  expireDate: null
})

const serverRules = {
  name: [{ required: true, message: '请输入服务器名称', trigger: 'blur' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    {
      validator: (rule, value, callback) => {
        if (serverForm.value.authType === 'password' && !value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  privateKey: [
    {
      validator: (rule, value, callback) => {
        if (serverForm.value.authType === 'key' && !value) {
          callback(new Error('请输入私钥'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 退出登录
const handleLogout = async () => {
  // 关闭所有终端连接
  activeTerminals.value = []
  await authStore.logout()
  router.push('/login')
}

// 打开终端
const openTerminal = (server) => {
  console.log('🔌 打开终端:', server.name)
  
  // 检查是否已经打开
  const existing = activeTerminals.value.find(t => t.serverId === server.id)
  if (existing) {
    // 切换到已有的标签页
    activeTabName.value = existing.id
    return
  }
  
  // 创建新的终端标签
  const terminalId = `terminal-${server.id}-${Date.now()}`
  activeTerminals.value.push({
    id: terminalId,
    serverId: server.id,
    serverName: server.name
  })
  activeTabName.value = terminalId
}

// 关闭终端
const closeTerminal = (terminalId) => {
  console.log('❌ 关闭终端:', terminalId)
  const index = activeTerminals.value.findIndex(t => t.id === terminalId)
  if (index > -1) {
    activeTerminals.value.splice(index, 1)
    
    // 如果还有其他标签，切换到最后一个
    if (activeTerminals.value.length > 0) {
      activeTabName.value = activeTerminals.value[activeTerminals.value.length - 1].id
    }
  }
}

// 编辑服务器
const editServer = (server) => {
  editingServer.value = server
  serverForm.value = {
    name: server.name,
    host: server.host,
    port: server.port,
    username: server.username,
    authType: server.auth_type,
    password: '',
    privateKey: '',
    groupName: server.group_name || 'default',
    expireDate: server.expire_date || null
  }
  showAddDialog.value = true
}

// 删除服务器确认
const deleteServerConfirm = async (server) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除服务器 "${server.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 关闭相关的终端
    activeTerminals.value = activeTerminals.value.filter(t => t.serverId !== server.id)
    
    await serversStore.removeServer(server.id)
  } catch (error) {
    // 用户取消
  }
}

// 提交表单
const handleSubmit = async () => {
  const valid = await serverFormRef.value?.validate()
  if (!valid) return

  submitting.value = true
  try {
    if (editingServer.value) {
      // 更新服务器
      await serversStore.updateServerById(editingServer.value.id, serverForm.value)
    } else {
      // 添加服务器
      await serversStore.addServer(serverForm.value)
    }
    closeDialog()
  } catch (error) {
    // 错误已在store中处理
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false
  editingServer.value = null
  serverForm.value = {
    name: '',
    host: '',
    port: 22,
    username: 'root',
    authType: 'password',
    password: '',
    privateKey: '',
    groupName: 'default',
    expireDate: null
  }
}

// 格式化到期日期显示
const formatExpireDate = (expireDate) => {
  if (!expireDate) return ''
  
  const expire = new Date(expireDate)
  const now = new Date()
  const diffTime = expire - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  // 格式化日期
  const year = expire.getFullYear()
  const month = expire.getMonth() + 1
  const day = expire.getDate()
  const dateStr = `${year}年${month}月${day}日`
  
  if (diffDays < 0) {
    // 已过期
    return `${dateStr}到期，已过期${Math.abs(diffDays)}天`
  } else if (diffDays === 0) {
    return `${dateStr}到期，今天到期`
  } else {
    return `${dateStr}到期，剩余${diffDays}天`
  }
}

// 获取到期状态的样式类
const getExpireClass = (expireDate) => {
  if (!expireDate) return ''
  
  const expire = new Date(expireDate)
  const now = new Date()
  const diffTime = expire - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays < 0) {
    return 'expired' // 已过期
  } else if (diffDays <= 7) {
    return 'expiring-soon' // 7天内到期
  } else if (diffDays <= 30) {
    return 'expiring-warning' // 30天内到期
  } else {
    return 'expiring-normal' // 正常
  }
}

onMounted(() => {
  console.log('🏠 主页加载')
  serversStore.fetchServers()
})
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.header-left h1 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-size: 14px;
  color: #666;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 320px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.sidebar-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.server-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.loading,
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
  gap: 10px;
}

.server-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.server-card:hover {
  background: #e4e7ed;
  transform: translateX(5px);
}

.server-card.active {
  background: #ecf5ff;
  border-color: #409eff;
}

.server-info {
  flex: 1;
}

.server-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.server-host {
  font-size: 12px;
  color: #909399;
}

.server-expire {
  font-size: 11px;
  margin-top: 5px;
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}

.server-expire.expiring-normal {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

.server-expire.expiring-warning {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.server-expire.expiring-soon {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
  font-weight: 600;
}

.server-expire.expired {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.2);
  font-weight: 600;
}

.server-actions {
  display: flex;
  gap: 5px;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.welcome {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
}

.welcome-icon {
  margin-bottom: 30px;
  color: #667eea;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
}

.welcome-title {
  font-size: 36px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 15px;
}

.welcome-subtitle {
  font-size: 16px;
  color: #666;
  margin-bottom: 50px;
}

.feature-cards {
  display: flex;
  gap: 30px;
  margin-bottom: 50px;
}

.feature-card {
  background: white;
  padding: 30px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
  width: 200px;
  transition: all 0.3s;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.feature-card h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 15px 0 10px;
}

.feature-card p {
  font-size: 13px;
  color: #909399;
  line-height: 1.6;
}

.stats-section {
  display: flex;
  align-items: center;
  gap: 40px;
  background: white;
  padding: 30px 60px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 40px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 48px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.stat-divider {
  width: 1px;
  height: 60px;
  background: #e4e7ed;
}

.quick-start {
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.8; }
}

.terminal-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-tabs) {
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
}

:deep(.el-tab-pane) {
  height: 100%;
}
</style>
